import re
import math

from core import DrawableText, Font, AppError

def keep_zh_cn(data:str):
    pattern = re.compile(r"[^\u4e00-\u9fa5！？]")
    return re.sub(pattern,"",data)

def keep_en_us(data:str):
    pattern = re.compile(r"[^a-zA-Z!?]")
    return re.sub(pattern,"",data)

def keep_number(data:str):
    pattern = re.compile(r"0-9")
    return re.sub(pattern,"",data)

def generate_text_image(name:str,font_zh:Font, font_en:Font ,default_size=20, max_width = 104) -> DrawableText:
    zh, en ,n = keep_zh_cn(name), keep_en_us(name), keep_number(name)
    if zh:
        font_size = default_size if len(zh) * default_size <= max_width else math.floor(max_width / len(zh)) 
        font = font_zh.loadFont(font_size)
        image = DrawableText(zh,font_size,font)
    elif en:
        font_size = default_size if len(en) * default_size <= max_width else math.floor(max_width / len(en))
        font = font_en.loadFont(font_size)
        image = DrawableText(en,font_size,font)
    elif n:
        font_size = default_size if len(n) * default_size <= max_width else math.floor(max_width / len(n))
        font = font_en.loadFont(font_size)
        image = DrawableText(n,font_size,font)
    else: raise AppError("bad_language","unsupported language in {text}, only zh-cn and en-us are supported".format(text=name))
    return image